package chen.web.util;

import java.io.CharArrayWriter;
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;

import chen.web.config.ConfigRepository;
import chen.web.config.SiteConfig;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;

public class FreeMarker {

	private static Configuration cfg;
	
	private static Configuration getConfiguration() throws IOException{
		if(cfg == null){
			synchronized(FreeMarker.class){
				if(cfg == null){
					cfg = new Configuration();
					File appDirectory = PathUtil.getAppDirectory();
					String templatePath = new StringBuffer().append(appDirectory.getAbsolutePath())
															.append(File.separatorChar)
															.append("WEB-INF")
															.append(File.separatorChar)
															.append("flt")
															.toString();
					File templateDirectory = new File(templatePath);
					cfg.setDirectoryForTemplateLoading(templateDirectory);
					cfg.setEncoding(Locale.SIMPLIFIED_CHINESE, "UTF-8");
				}
			}
		}
		return cfg;
	}
	
	public static String process(String template, Map<String, Object> rootMap){
		SiteConfig siteConfig = ConfigRepository.instance().get(SiteConfig.class);
		rootMap.put("baseURL", siteConfig.getBaseURL());
		rootMap.put("siteName", siteConfig.getSiteName());
		CharArrayWriter out = new CharArrayWriter();
		try {
			getConfiguration().getTemplate(template).process(rootMap, out);
			out.close();
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		char[] result = out.toCharArray();
		return String.valueOf(result);
	}
}
